package com.sn.author.monitor.handler;

import com.alibaba.fastjson.JSON;
import com.sn.author.common.context.SpringContext;
import com.sn.author.common.enums.LoginStatusEnum;
import com.sn.author.common.sdk.AbstractResponse;
import com.sn.author.common.sdk.entity.AbstractResult;
import com.sn.author.common.sdk.request.LoginDyRequest;
import com.sn.author.common.sdk.response.LoginDyResponse;
import com.sn.author.dao.ImportAccountMapper;
import com.sn.author.domain.entity.ImportAccount;
import com.sn.author.domain.taskEntity.TaskModel;
import com.sn.author.domain.vo.LoginVo;
import com.sn.author.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @Author xiaom
 * @Date 2020/9/22 17:12
 * @Version 1.0.0
 * @Description <>
 **/
@Slf4j
public class LoginHandler extends AbsHandler {

    public LoginHandler(TaskModel taskModel) {
        super(taskModel);
    }

    @Override
    String getSuccessMessage() {
        LoginVo loginVo = JSON.parseObject(taskModel.getTaskParam().toString(),LoginVo.class);
        return "登录账号:[" + loginVo.getUserName() + "] 成功,cookie已经刷新";
    }

    @Override
    String getErrorMessage(String errmsg) {
        LoginVo loginVo = JSON.parseObject(taskModel.getTaskParam().toString(),LoginVo.class);
        return "账号:[" + loginVo.getUserName() + "] 登录失败 错误信息:" + errmsg;
    }

    @Override
    public void execute() throws Exception {
        //访问抖音api 登录账号获取cookie
        try {
            LoginDyResponse response = requestApi();
            if(response == null){
                throw new Exception("抖音login api返回了空/错误的结果 响应值:" + JSON.toJSONString(response));
            }
            if(!response.getSuccess()){
                pushMessage("登录异常 -> " + response.getMessage());
                return;
            }
            //更新账号信息
            saveInfo(response.getData());
            //推送消息
            pushMessage(getSuccessMessage());
        }catch (Exception e){
            pushMessage(getErrorMessage(e.getMessage()));
        }

    }

    @Override
    public void responseAfter(AbstractResponse response) {

    }

    private void saveInfo(LoginDyResponse.ResponseMsgResult data) throws Exception {
        if(data == null){
            throw new Exception("抖音api 登录 返回数据为空");
        }
        //获取对应的mybatis mapper文件
        ImportAccountMapper mapper = SpringContext.getBean(ImportAccountMapper.class);
        //转换参数模型
        LoginVo loginVo = JSON.parseObject(taskModel.getTaskParam().toString(),LoginVo.class);
        //更新信息
        ImportAccount importAccount = mapper.selectByPhone(loginVo.getUserName());
        if(importAccount == null){
            throw new Exception("登录了一个不存在的手机号码,请检查是否已被删除 phone:[ " + loginVo.getUserName() + "]");
        }

        importAccount.setUrlParam(data.getUrlParam());
        importAccount.setHeader(data.getHeader());
        importAccount.setLoginStatus(LoginStatusEnum.LOGIN.getStatus());
        importAccount.setLastLoginTime(DateUtils.formatYMDHMS(new Date()));
        mapper.updateByPrimaryKeySelective(importAccount);

        log.info("账号:[{}] 登录抖音成功,cookie已刷新",loginVo.getUserName());
    }

    public LoginDyResponse requestApi(){
        try {
            ImportAccountMapper mapper = SpringContext.getBean(ImportAccountMapper.class);
            LoginVo loginVo = JSON.parseObject(taskModel.getTaskParam().toString(),LoginVo.class);
            ImportAccount importAccount = mapper.selectByPhone(loginVo.getUserName());
            LoginDyRequest request = new LoginDyRequest();
            request.setPassword(loginVo.getPassword());
            request.setPhone(loginVo.getUserName());
            request.setDeviceId(importAccount.getDeviceId());
            return getClient().execute(request);
        } catch (Exception e) {
            log.error("调用抖音登录api失败 message:{}",e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void responseErrAfter(String errMsg) {

    }
}
